import  MysFpDB  from "../model/MysFpDB.js"
export class Handler extends plugin {
  constructor() {
    super({
      name: '小新枝',
      priority: -Infinity,
      namespace: '@小新枝',
      handler: [{
        key: 'mys.req.err',
        fn: 'mysReqErrHandler'
      }]
    })
  }

  // 接受的参数
  async mysReqErrHandler (e, args, reject) {
    logger.mark('绑定设备调用....')

    let { data, mysApi, type } = args
    if (![1034, 5003, 10035, 10041].includes(Number(args?.res?.retcode))) {
      return reject()
    }
    const match = args.mysApi.cookie.match(/ltuid=(\d+)/)
    let fp = await MysFpDB.findfp(match[1])
    logger.debug(fp)
    if (!fp) return reject()
    e.fp = fp
    try {
      if (data?.headers) {
        data.headers = {
          ...data.headers,
          'x-rpc-device_fp': fp.data.device_fp
        }
      } else {
        if (!data) data = {}
        data.headers = { 'x-rpc-device_fp': fp.data.device_fp }
      }
      if(fp.data?.device_id) data.headers['x-rpc-device_id'] = fp.data.device_id
      let res = await mysApi.getData(type, data)
      if (![1034, 5003, 10035, 10041].includes(Number(res?.retcode))) {
        logger.debug(res)
        return res
      }
      return reject()
    } catch (err) { logger.info(err) }
    return reject()
  }
}
